package study.doc.word.support;

import cn.hutool.core.io.resource.ResourceUtil;
import uk.ac.ed.ph.snuggletex.SnuggleEngine;
import uk.ac.ed.ph.snuggletex.SnuggleInput;
import uk.ac.ed.ph.snuggletex.SnuggleSession;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;

public class MmlUtils {

    private static TransformerFactory TF_FACTORY = TransformerFactory.newInstance();

    private static InputStream IS = ResourceUtil.getStream("config/MML2OMML.XSL");

    /**
     * latex 转换 mml
     *
     * @param latex
     * @return mml
     */
    public static String latex2mml(String latex) {
        //引擎
        SnuggleEngine engine = new SnuggleEngine();
        //会话
        SnuggleSession session = engine.createSession();
        //
        String mml;
        try {
            //生成
            SnuggleInput input = new SnuggleInput(latex);
            session.parseInput(input);
            mml = session.buildXMLString();
        } catch (Exception ex) {
            throw new RuntimeException("latex 转换 mml 异常: ", ex);
        }
        return mml;
    }

    /**
     * mml 转换 omml
     *
     * @param mml
     * @return omml
     */
    public static String mml2omml(String mml) {
        String ooml;
        try (StringWriter writer = new StringWriter();
             StringReader reader = new StringReader(mml)) {
            //
            StreamSource source = new StreamSource(reader);
            StreamResult result = new StreamResult(writer);
            //
            StreamSource styleSource = new StreamSource(IS);
            Transformer transformer = TF_FACTORY.newTransformer(styleSource);
            transformer.transform(source, result);
            //
            ooml = writer.toString();
        } catch (Exception ex) {
            throw new RuntimeException("mml 转换 ooml 异常: ", ex);
        }
//        ooml = ooml.replace("\n", "");
        //
        return ooml;
    }
}
